using System;
using System.Collections.Generic;
using System.Linq;

namespace Catastrophe.Common.Tools.Cals
{
	public class CpkCal
	{
		private const int SavePoint = 3;

		public static double GetStdev(IEnumerable<double> dataBuf)
		{
			if (dataBuf.Count() <= 1)
			{
				return 0.0;
			}
			double avg = dataBuf.Average();
			double num = dataBuf.Sum((double d) => Math.Pow(d - avg, 2.0));
			return Math.Round(Math.Sqrt(num / (double)(dataBuf.Count() - 1)), 3);
		}

		public static double GetRange(IEnumerable<double> dataBuf)
		{
			if (dataBuf.Count() == 0)
			{
				return 0.0;
			}
			double avg = dataBuf.Average();
			double num = dataBuf.Sum((double d) => Math.Pow(d - avg, 2.0));
			return Math.Round(Math.Sqrt(num / (double)dataBuf.Count()), 3);
		}

		public static double GetCp(double limitUp, double limitDown, IEnumerable<double> dataBuf)
		{
			if (dataBuf.Count() <= 1)
			{
				return 0.0;
			}
			double num = 0.0;
			num = limitUp - limitDown;
			double avg = dataBuf.Average();
			double num2 = Math.Round(Math.Sqrt(dataBuf.Sum((double d) => Math.Pow(d - avg, 2.0)) / (double)(dataBuf.Count() - 1)), 3);
			if (num2 == 0.0)
			{
				return 0.0;
			}
			return num / (6.0 * num2);
		}

		public static double GetCpkU(double limitUp, IEnumerable<double> dataBuf)
		{
			if (dataBuf.Count() <= 1)
			{
				return 0.0;
			}
			double avg = dataBuf.Average();
			double num = limitUp - avg;
			double num2 = Math.Round(Math.Sqrt(dataBuf.Sum((double d) => Math.Pow(d - avg, 2.0)) / (double)(dataBuf.Count() - 1)), 3);
			if (num2 == 0.0)
			{
				return 0.0;
			}
			return num / (3.0 * num2);
		}

		public static double GetCpkL(double limitDown, IEnumerable<double> dataBuf)
		{
			if (dataBuf.Count() <= 1)
			{
				return 0.0;
			}
			double avg = dataBuf.Average();
			double num = avg - limitDown;
			double num2 = Math.Round(Math.Sqrt(dataBuf.Sum((double d) => Math.Pow(d - avg, 2.0)) / (double)(dataBuf.Count() - 1)), 3);
			return num / (3.0 * num2);
		}

		public static double GetCpk(double cpkU, double cpkL)
		{
			return Math.Min(cpkU, cpkL);
		}

		public static double GetCpk(double limitUp, double limitDown, IEnumerable<double> dataBuf)
		{
			if (dataBuf.Count() <= 1)
			{
				return 0.0;
			}
			double num = 0.0;
			double num2 = 0.0;
			double avg = dataBuf.Average();
			double num3 = avg - limitDown;
			double num4 = limitUp - avg;
			double num5 = Math.Round(Math.Sqrt(dataBuf.Sum((double d) => Math.Pow(d - avg, 2.0)) / (double)(dataBuf.Count() - 1)), 3);
			if (num5 == 0.0)
			{
				return 0.0;
			}
			num = num3 / (3.0 * num5);
			num2 = num4 / (3.0 * num5);
			return Math.Min(num2, num);
		}
	}
}
